package com.finance.cooperate.feature.service.impl;

import com.finance.cooperate.common.utils.DateUtils;
import com.finance.cooperate.common.utils.StringUtil;
import com.finance.cooperate.dao.entity.primary.Apply;
import com.finance.cooperate.dao.local.scope.CooperateRequestScope;
import com.finance.cooperate.dao.repository.primary.ApplyRepository;
import com.finance.cooperate.dao.repository.primary.BorrowingRepository;
import com.finance.cooperate.dao.support.dto.BorrowingApplyDTO;
import com.finance.cooperate.feature.dto.BorrowingDTO;
import com.finance.cooperate.feature.service.BorrowingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName BorrowingServiceImpl
 * @Description TODO
 * @Author shen
 * @Date 2023/8/7 09:34
 * @Modify ...
 */
@Slf4j
@Service
public class BorrowingServiceImpl implements BorrowingService {

    @Autowired
    private BorrowingRepository borrowingRepository;
    @Autowired
    private CooperateRequestScope requestScope;

    @Autowired
    private ApplyRepository applyRepository;

    @Override
    public Long getCurLoanNum(String uid) {

        return requestScope.getLoanNum();
    }



    @Override
    public Integer sameIpOverdueStatue(String uid) {

        Integer sameIpOverdueStatue = -1;

        // 先获取到用户ip
        String applyId = requestScope.getApplyId();
        Date lastSubmitTime = requestScope.getLastSubmitTime();

        if (!StringUtil.isEmptyOrNvl(applyId)) {

            Optional<Apply> optional = applyRepository.findById(applyId);

            if (optional.isPresent()) {

                Apply apply = optional.get();

                String ip = apply.getIp();

                // 根据ip查询是否有到期用户
                if (!StringUtil.isEmptyOrNvl(ip)) {

                    sameIpOverdueStatue = borrowingRepository.sameIpOverdueCount(lastSubmitTime, ip, uid);

                }
            }
        }

        return sameIpOverdueStatue;
    }


    @Override
    public BorrowingDTO getInfo(String uid) {

        BorrowingDTO dto = new BorrowingDTO();

        // 如果是首贷，直接跳过
        if (requestScope.getLoanNum() <= 1L) {
            return dto;
        }

        List<BorrowingApplyDTO> borrowList = borrowingRepository.getBorrowLt(uid, requestScope.getLoanNum().intValue());

        if (borrowList != null && borrowList.size() > 0){

            Integer maxOverdueDays = null;

            Integer minOverdueDays = null;

            int sumOverdueDays = 0;

            Integer maxPrepaymentHours = null;
            Integer minPrepaymentHours = null;

            int sumPrepaymentHours = 0;
            int sumPrepaymentHoursCount = 0;

            int sumLoanAndRiskIntervalHours = 0;
            int sumLoanAndRiskIntervalHoursCount = 0;

            for (BorrowingApplyDTO b: borrowList) {

                Integer overdueDays = b.getOverdueDay();

                if (overdueDays != null && overdueDays < 0) {
                    overdueDays = 0;
                }

                if (overdueDays != null) {

                    if (maxOverdueDays == null || maxOverdueDays < overdueDays) {
                        maxOverdueDays = overdueDays;
                    }

                    if (minOverdueDays == null || minOverdueDays > overdueDays) {
                        minOverdueDays = overdueDays;
                    }

                    sumOverdueDays += overdueDays;

                }

                // 应还时间
                Date repaymentTime = b.getRepaymentTime();
                // 还清时间
                Date payoffTime = b.getPayoffTime();

                if (repaymentTime != null && payoffTime != null) {

                    Integer timeDiffHours = DateUtils.getTimeDiffHours(payoffTime, repaymentTime);


                    if (timeDiffHours >= 0) {
                        if (maxPrepaymentHours == null || maxPrepaymentHours < timeDiffHours) {
                            maxPrepaymentHours = timeDiffHours;
                        }

                        if (minPrepaymentHours == null || minPrepaymentHours > timeDiffHours) {
                            minPrepaymentHours = timeDiffHours;
                        }

                        sumPrepaymentHours += timeDiffHours;
                        sumPrepaymentHoursCount += 1;
                    }

                }

                // 通过时间
                Date throughTime = b.getThroughTime();
                // 订单创建时间
                Date createTime = b.getCreateTime();

                if (throughTime != null && createTime != null) {

                    Integer timeDiffHours = DateUtils.getTimeDiffHours(throughTime, createTime);


                    if (timeDiffHours >= 0) {

                        sumLoanAndRiskIntervalHours += timeDiffHours;
                        sumLoanAndRiskIntervalHoursCount += 1;
                    }

                }

            }


            dto.setMaxOverdueDays(maxOverdueDays);
            dto.setMinOverdueDays(minOverdueDays);
            dto.setAvgOverdueDays(sumOverdueDays / borrowList.size());


            dto.setMaxPrepaymentHours(maxPrepaymentHours);
            dto.setMinPrepaymentHours(minPrepaymentHours);

            if (sumLoanAndRiskIntervalHoursCount > 0) {
                dto.setAvgLoanAndRiskIntervalHours(sumLoanAndRiskIntervalHours / sumLoanAndRiskIntervalHoursCount);
            }

            if (sumPrepaymentHoursCount > 0) {
                dto.setAvgPrepaymentHours(sumPrepaymentHours / sumPrepaymentHoursCount);
            }


            // 上次结清时间
            try {

                BorrowingApplyDTO applyDTO = borrowList.get(0);

                Date payoffTime = applyDTO.getPayoffTime();

                if (!StringUtil.isEmptyOrNvl(payoffTime)) {
                    Map<String, Integer> element = DateUtils.getDateElement(payoffTime);

                    dto.setLastPayoffHour(element.get(DateUtils.HOUR));
                }


                // 通过时间
                Date throughTime = applyDTO.getThroughTime();
                // 订单创建时间
                Date createTime = applyDTO.getCreateTime();

                Integer hours = DateUtils.getTimeDiffHours(throughTime, createTime);

                dto.setLastLoanAndRiskIntervalHours(hours);

            } catch (Exception e) {
                log.error(e.toString(), e);
            }


        }



        return dto;
    }
}
